#ifndef _BEE_H
#define _BEE_H

extern void pageInfoAdd(char *info);

// static ledc_timer_config_t ledcTimer;
static ledc_channel_config_t ledcChan;

static TaskHandle_t beeOpTaskH;

void beeInit();
void beeStart();
void beeStop();
void beeOpTask();

void beeInit() {
	dispInitInfo("Init speaker...");
	ledc_timer_config_t ledcTimer = {
		.duty_resolution	= LEDC_TIMER_13_BIT,				// 设置分辨率,最大为2^13-1
		.freq_hz 			= stGroup[ST_BEE_FREQ].intValue,	// PWM信号频率
		.speed_mode			= LEDC_HIGH_SPEED_MODE,				// 定时器模式（“高速”或“低速”）
		.timer_num			= LEDC_TIMER_0,						// 设置定时器源（0-3）
		.clk_cfg			= LEDC_AUTO_CLK,					// 配置LEDC时钟源（这里是自动选择）
	};
	ledc_timer_config(&ledcTimer);

	ledc_channel_config_t ledcChan = {
		.channel    = LEDC_CHANNEL_0,			// LEDC通道(0-7)
		.duty       = 0,						// 初始化占空比
		.gpio_num   = CONFIG_PIN_SPEAKER,		// pwm输出的gpio
		.speed_mode = LEDC_HIGH_SPEED_MODE,		// 高速还是低速模式
		.hpoint     = 0,						// LEDC通道hpoint值
		.timer_sel  = LEDC_TIMER_0				// LEDC依赖的定时器
	};
	ledc_channel_config(&ledcChan);
	
	dispInitInfo("Speaker init done.");
	// 蜂鸣器
	xTaskCreatePinnedToCore(beeOpTask, "beeOpTask", 1024 * 1, NULL, 0, &beeOpTaskH, 1);
}

void beeOpTask() {
	uint32_t bit;
	while(1) {
		xTaskNotifyWait(
			0x00,
			ULONG_MAX,
			&bit,
			portMAX_DELAY
		);
		if((bit & BIT0) != 0) {
			ledc_set_duty(ledcChan.speed_mode, ledcChan.channel, stGroup[ST_BEE_DUTY].intValue);
			ledc_update_duty(ledcChan.speed_mode, ledcChan.channel);
		}
		if((bit & BIT1) != 0) {
			ledc_set_duty(ledcChan.speed_mode, ledcChan.channel, 0);
			ledc_update_duty(ledcChan.speed_mode, ledcChan.channel);
		}
	}
	vTaskDelete(NULL);
}

void beeStart() {
	xTaskNotify(beeOpTaskH, BIT0, eSetValueWithoutOverwrite);
}

void beeStop() {
	xTaskNotify(beeOpTaskH, BIT1, eSetValueWithoutOverwrite);
}

#endif